package com.wanpinghui.supplier.widgets;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.View;

import com.wanpinghui.supplier.R;

import java.lang.ref.WeakReference;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/21
 ***/

public class TopWarningTextView extends AppCompatTextView {
    private MHandler handler;
    private int textViewHeight;

    public TopWarningTextView(Context context) {
        super(context);
        init();
    }

    public TopWarningTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TopWarningTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        handler = new MHandler(this);
    }

    public void show() {
        handler.removeMessages(1);
        if (textViewHeight == 0) {
            int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            measure(width, height);
            textViewHeight = getMeasuredHeight();
        }
        Animator anim = AnimatorInflater.loadAnimator(getContext(), R.animator.warning_text_show);
        setPivotY(0);
        //显示的调用invalidate
        anim.setTarget(this);
        anim.start();
        anim.setDuration(300);
        setVisibility(VISIBLE);
        anim.start();
        handler.sendEmptyMessageDelayed(1, 3000);
    }

    public void hide() {
//        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(this,"scaleY", 1, 0);
//        objectAnimator.setDuration(300);
//        objectAnimator.start();
        if (getVisibility() == VISIBLE) {
            Animator anim = AnimatorInflater.loadAnimator(getContext(), R.animator.warning_text_hide);
            setPivotY(0);
            //显示的调用invalidate
            anim.setTarget(this);
            anim.start();
            anim.setDuration(300);
            setVisibility(VISIBLE);
            anim.start();
        }
    }

    private static class MHandler extends Handler {
        private WeakReference<TopWarningTextView> reference;

        public MHandler(TopWarningTextView textView) {
            reference = new WeakReference<>(textView);
        }

        @Override
        public void handleMessage(Message msg) {
            TopWarningTextView textView = reference.get();
            if (textView != null) {
                if (msg.what == 1) {
                    textView.hide();
                } else if (msg.what == 2) {
                    textView.setVisibility(INVISIBLE);
                }
            }
        }
    }
}
